﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Utilities;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.PlcService
{
    public class ExitService
    {
        #region 成员实例
        OrderDao orderDao = new OrderDao();
        #endregion


        /// <summary>
        /// 执行出站
        /// </summary>
        /// <param name="station"></param>
        /// <returns></returns>
        public byte StationExit(string station, byte[] bytes, string code, string result, string operationId)
        {
            DateTime now = DateTime.Now;

            try
            {
                if (station.Contains("NG"))
                {
                    // 记录NG工位出站
                    orderDao.NgStationSave(new NgStation()
                    {
                        CreateTime = now,
                        Station = station,
                        TraceId = code,
                        Status = "1"
                    });
                }
                else
                {
                    orderDao.UpdateStationEndTime(code, result, station, now, operationId);

                    OrderProduction(station);
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"[{station}]触发出站失败，原因是[{ex.Message}]");
            }

            return 2;
        }

        /// <summary>
        /// 当前存在工单时首工序产量统计
        /// </summary>
        /// <param name="station"></param>
        private void OrderProduction(string station)
        {
            List<string> startStation = new List<string>()
            {
                SystemConstant.OP10L,
                SystemConstant.OP10R,
            };

            if (!startStation.Contains(station))
                return;

            OrderSingletonModel orderSingletonModel = OrderSingleton.Instance.Where(x => x.MaterialId.Equals(MappingTable.GetMaterialByStation(station))).FirstOrDefault();

            if (orderSingletonModel == null)
                return;

            orderDao.UpdateProduction(orderSingletonModel.OrderId);

            OrderSingleton.AddNumNow(orderSingletonModel.OrderId);
        }
    }
}
